package com.anonymous.community.ui.home;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anonymous.community.R;
import com.anonymous.community.model.Post;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {

    private List<Post> postList;
    private OnPostInteractionListener listener;
    private SimpleDateFormat dateFormat;

    public interface OnPostInteractionListener {
        void onLikeClick(int position);
        void onCommentClick(int position);
        void onShareClick(int position);
        void onMoreClick(int position);
        void onUserClick(int position);
    }
    
    public Post getPost(int position) {
        if (position >= 0 && position < postList.size()) {
            return postList.get(position);
        }
        return null;
    }

    public PostAdapter() {
        this.postList = new ArrayList<>();
        this.dateFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
    }

    public void setOnPostInteractionListener(OnPostInteractionListener listener) {
        this.listener = listener;
    }

    public void setPosts(List<Post> posts) {
        this.postList = posts;
        notifyDataSetChanged();
    }

    public void addPosts(List<Post> posts) {
        int startPosition = postList.size();
        this.postList.addAll(posts);
        notifyItemRangeInserted(startPosition, posts.size());
    }

    public void clearPosts() {
        this.postList.clear();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_post, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        Post post = postList.get(position);
        holder.bind(post, position);
    }

    @Override
    public int getItemCount() {
        return postList.size();
    }

    class PostViewHolder extends RecyclerView.ViewHolder {
        private ImageView userAvatar;
        private TextView username;
        private TextView postTime;
        private TextView postContent;
        private TextView categoryTag;
        private ImageView moreButton;
        private ImageView likeIcon;
        private TextView likeCount;
        private TextView commentCount;
        private TextView shareCount;
        private LinearLayout likeLayout;
        private LinearLayout commentLayout;
        private LinearLayout shareLayout;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            userAvatar = itemView.findViewById(R.id.user_avatar);
            username = itemView.findViewById(R.id.username);
            postTime = itemView.findViewById(R.id.post_time);
            postContent = itemView.findViewById(R.id.post_content);
            categoryTag = itemView.findViewById(R.id.category_tag);
            moreButton = itemView.findViewById(R.id.more_button);
            likeIcon = itemView.findViewById(R.id.like_icon);
            likeCount = itemView.findViewById(R.id.like_count);
            commentCount = itemView.findViewById(R.id.comment_count);
            shareCount = itemView.findViewById(R.id.share_count);
            likeLayout = itemView.findViewById(R.id.like_layout);
            commentLayout = itemView.findViewById(R.id.comment_layout);
            shareLayout = itemView.findViewById(R.id.share_layout);
        }

        public void bind(Post post, int position) {
            // 设置用户信息
            if (post.isAnonymous()) {
                username.setText("匿名用户");
                userAvatar.setImageResource(R.drawable.ic_anonymous_24);
            } else {
                username.setText(post.getUsername());
                // 这里可以加载真实头像，暂时使用默认头像
                userAvatar.setImageResource(R.drawable.ic_person);
            }

            // 设置时间
            String timeText = formatTime(post.getTimestamp());
            postTime.setText(timeText);

            // 设置内容
            postContent.setText(post.getContent());

            // 设置分类标签
            if (post.getCategory() != null && !post.getCategory().isEmpty()) {
                categoryTag.setText("#" + post.getCategory());
                categoryTag.setVisibility(View.VISIBLE);
            } else {
                categoryTag.setVisibility(View.GONE);
            }

            // 设置互动数据
            likeCount.setText(formatCount(post.getLikes()));
            commentCount.setText(formatCount(post.getComments()));
            shareCount.setText(formatCount(post.getShares()));

            // 设置点赞状态
            if (post.isLiked()) {
                likeIcon.setImageResource(R.drawable.ic_like_filled);
                likeIcon.setColorFilter(itemView.getContext().getResources().getColor(R.color.colorAccent));
            } else {
                likeIcon.setImageResource(R.drawable.ic_like_outline);
                likeIcon.setColorFilter(itemView.getContext().getResources().getColor(R.color.colorGray));
            }

            // 设置点击事件
            likeLayout.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onLikeClick(position);
                }
            });

            commentLayout.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onCommentClick(position);
                }
            });

            shareLayout.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onShareClick(position);
                }
            });

            moreButton.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onMoreClick(position);
                }
            });

            userAvatar.setOnClickListener(v -> {
                if (listener != null && !post.isAnonymous()) {
                    listener.onUserClick(position);
                }
            });
            
            // 卡片整体点击跳转到详情页
            itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onCommentClick(position);
                }
            });
        }

        private String formatTime(long timestamp) {
            long now = System.currentTimeMillis();
            long diff = now - timestamp;

            if (diff < 60000) { // 1分钟内
                return "刚刚";
            } else if (diff < 3600000) { // 1小时内
                return (diff / 60000) + "分钟前";
            } else if (diff < 86400000) { // 1天内
                return (diff / 3600000) + "小时前";
            } else if (diff < 604800000) { // 1周内
                return (diff / 86400000) + "天前";
            } else {
                return dateFormat.format(new Date(timestamp));
            }
        }

        private String formatCount(int count) {
            if (count < 1000) {
                return String.valueOf(count);
            } else if (count < 10000) {
                return String.format(Locale.getDefault(), "%.1fK", count / 1000.0);
            } else {
                return String.format(Locale.getDefault(), "%.1fW", count / 10000.0);
            }
        }
    }
}